package com.jdew.thkj.activity;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.adapter.SuperSearchAdapter;
import com.jdew.thkj.adapter.SuperSearchAdapter2;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.SuperSearchBean;
import com.jdew.thkj.bean.SuperSearchBean2;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/8/9.
 */

public class SearchActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.price)
    RadioButton price;
    @Bind(R.id.main_tab)
    RadioGroup main_tab;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.swipeloadlayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.noresult)
    TextView noresult;
    @Bind(R.id.result_view)
    RelativeLayout resultView;
    private Boolean paixun = false;
    public String sortType = "tk_total_sales";
    public String keywords = ".";
    public boolean HasCoupon = true;
    public Dialog mWeiboDialog;
    private int page = 1;
    public List<SuperSearchBean.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> list = new ArrayList<>();
    public List<SuperSearchBean2.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> list2 = new ArrayList<>();
    private SuperSearchAdapter adapter;
    private SuperSearchAdapter2 adapter2;
    private boolean isLoading = false;
    private String itemid;

    @Override
    public int bindLayout() {
        return R.layout.activity_search;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        keywords = getIntent().getStringExtra("result");
        title.setText(keywords);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        RadioButton rb = (RadioButton) main_tab.getChildAt(0);
        rb.setChecked(true);
        adapter = new SuperSearchAdapter(this, list);
        adapter2 = new SuperSearchAdapter2(this, list2);
        price.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!paixun) {
                    sortType = "price_des";
                    price.setText("价格(降)");
                    paixun = true;
                } else {
                    sortType = "price_asc";
                    price.setText("价格(升)");
                    paixun = false;
                }
                RequestData();
            }
        });
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(SearchActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    itemid = list.get(position).getNum_iid() + "";
                    toDetail();
                }
            }
        });
        adapter2.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(SearchActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    itemid = list2.get(position).getNum_iid() + "";
                    toDetail();
                }
            }
        });
        setRcycleview(recycleView, adapter);
        setRecycleView();
        RequestData();
        initRefresh();
        setListener();
    }

    //设置监听
    private void setListener() {
        //RadioGroup的事件监听
        main_tab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                page = 1;
                for (int index = 0; index < main_tab.getChildCount(); index++) {
                    RadioButton rb = (RadioButton) main_tab.getChildAt(index);
                    if (rb.isChecked()) {
                        gerSelected(index);
                        break;
                    }
                }
            }
        });
    }

    public void gerSelected(int i) {
        if (i == 0) {
            price.setText("价格");
            sortType = "tk_total_sales";
        } else if (i == 1) {
            price.setText("价格");
            sortType = "tk_rate_des";
        } else if (i == 2) {
            if (!paixun) {
                sortType = "price_des";
            } else {
                sortType = "price_asc";
            }
        } else if (i == 3) {
            price.setText("价格");
            sortType = "total_sales_des";
        }
        RequestData();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.network_view: {
                page = 1;
                RequestData();
            }
            break;
            default:
                break;
        }
    }

    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
            return;
        }
        if(keywords.length()>=10){
            HasCoupon=false;
        }
        if (null == mWeiboDialog || !mWeiboDialog.isShowing()) {
            mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        }
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).Getlookups(keywords, sortType, page + "", HasCoupon,RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"q"+keywords.trim()+"sort"+sortType+"PageIndex"+page+"HasCoupon"+HasCoupon)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JSONObject obj) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (obj.getString("code").equals("0")) {
                    list2.clear();
                    try {
                        SuperSearchBean bean = JSONObject.parseObject(obj.toString(), SuperSearchBean.class);
                        if ((null == bean.getData() || null == bean.getData().getTbk_dg_material_optional_response().getResult_list()) && page == 1) {
                            swipeRefreshLayout.setVisibility(View.GONE);
                            resultView.setVisibility(View.VISIBLE);
                            noresult.setText("未查询到" + "“" + keywords + "”" + "相关的产品");
                            return;
                        } else if (null == bean.getData() || null == bean.getData().getTbk_dg_material_optional_response().getResult_list()) {
                            adapter.changeMoreStatus(adapter.NO_LOAD_MORE);
                            swipeRefreshLayout.setRefreshing(false);
                            return;
                        }
                        if (page == 1) {
                            list.clear();
                        }
                        swipeRefreshLayout.setVisibility(View.VISIBLE);
                        list.addAll(bean.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data());
                        adapter.setDataList(list);
                        if(list.size()%30!=0){
                            isLoading = true;
                            adapter.changeMoreStatus(adapter.NO_LOAD_MORE);
                            swipeRefreshLayout.setRefreshing(false);
                            return;
                        }
                        isLoading = false;
                        adapter.changeMoreStatus(adapter.LOADING_MORE);
                        swipeRefreshLayout.setRefreshing(false);
                    } catch (Exception e) {
                       if(list.size()!=0){
                           adapter.changeMoreStatus(adapter.NO_LOAD_MORE);
                           swipeRefreshLayout.setRefreshing(false);
                           return;
                       }
                        SuperSearchBean2 bean2 = JSONObject.parseObject(obj.toString(), SuperSearchBean2.class);
                        if (null == bean2.getData() || null == bean2.getData().getTbk_dg_material_optional_response().getResult_list()) {
                            list2.clear();
                            adapter2.setDataList(list2);
                            noresult.setVisibility(View.VISIBLE);
                            noresult.setText("未查询到" + "“" + keywords + "”" + "相关的产品");
                            return;
                        }else if (null == bean2.getData() || null == bean2.getData().getTbk_dg_material_optional_response().getResult_list()) {
                            adapter2.changeMoreStatus(adapter2.NO_LOAD_MORE);
                            swipeRefreshLayout.setRefreshing(false);
                            return;
                        }
                        if (page == 1) {
                            list2.clear();
                        }
                        list2.add(bean2.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data());
                        adapter2.setDataList(list2);
                        setRcycleview(recycleView, adapter2);
                        isLoading = false;
                        adapter.changeMoreStatus(adapter.LOADING_MORE);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }
            }
        });
    }

    private void initRefresh() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                RequestData();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void toDetail() {
        Bundle b = new Bundle();
        b.putSerializable("itemId", itemid);
        startActivity(TbProductDetailActivity.class, b);
    }

    public void setRecycleView() {
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = null;
                if (layoutManager instanceof LinearLayoutManager) {
                    linearManager = (LinearLayoutManager) layoutManager;
                }
                int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        page++;
                        RequestData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }
}
